package com.beamfield.controller.manage.sys;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.beamfield.common.ApiResult;
import com.beamfield.common.ApplicationException;
import com.beamfield.common.CommonUtils;
import com.beamfield.common.PageResult;
import com.beamfield.controller.common.BaseController;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.ProjectDetail;
import com.beamfield.modelVo.ProductDrawingVO;
import com.beamfield.modelVo.ProductSuppliesVo;
import com.beamfield.service.manage.sys.ProjectService;

/**
 * 工程管理
 *
 * @author mintonzhang@163.com
 * @date 2018年6月11日
 */
@RestController
@RequestMapping("/cms")
public class ProjectController extends BaseController {

    @Resource(name = "unitProjectService")
    private ProjectService projectService;

    /**
     * 获取所有项目
     *
     * @param req
     * @return
     * @date 2018年6月13日
     * @author mintonzhang@163.com
     */
    @RequestMapping("/sys/getProject")
    public PageResult getProject(HttpServletRequest req) {
        return projectService.getProject(getBeamId(req));
    }

    @RequestMapping("/sys/getProductDrawing")
    public PageResult getProductDrawing(HttpServletRequest req,String offset, String limit) {
        return projectService.getProductDrawing(offset, limit, getBeamId(req));
    }

    @RequestMapping("/sys/project_list")
    public ModelAndView project() {
        return new ModelAndView();
    }

    @RequestMapping("/sys/project_detail")
    public ModelAndView detail() {
        return new ModelAndView();
    }

    @RequestMapping("/sys/project_supplies")
    public ModelAndView supplies() {
        return new ModelAndView();
    }

    @RequestMapping("/sys/drawingManage")
    public ModelAndView drawingManage() {
        return new ModelAndView();
    }

    /**
     * 获取不同梁型
     * @param request
     * @return
     * @author anruoxin
     * 2019年4月23日
     */
    @RequestMapping(value = "/sys/getProductType",method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getProductType(HttpServletRequest req){

        return new ApiResult(projectService.getProductType(getBeamId(req)));
    }

    @RequestMapping(value = "/sys/saveProductDrawing",method = RequestMethod.POST)
    public ApiResult saveProductDrawing(HttpServletRequest request, String product_id, Long zjsgtz_id, Long zyzds_id){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        if(zyzds_id == null || zjsgtz_id == null || CommonUtils.checkMissParam(product_id)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try{
            result = projectService.saveProductDrawing( userId, beamId, product_id, zjsgtz_id, zyzds_id);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }
        if(result == 0){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }else{
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"新增成功");
        }
    }

    /**
     * 获取初始化处理进度
     * @param request
     * @return
     */
    @RequestMapping(value = "/sys/getProgressData",method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getProgressData(HttpServletRequest request){
        Map<String,Double> resMap = new HashMap<>();
        Object progress = request.getSession().getAttribute("init_project_progress");
        resMap.put("progressValue", progress == null ? 0L : (Double) progress);
        return new ApiResult(resMap);
    }

    /**
     * 修改/添加项目 project_id 是空位修改 否则为添加
     *
     * @param req
     * @param project_time
     * @param project_id
     * @param name
     * @param pStr
     * @return
     * @date 2018年6月13日
     * @author mintonzhang@163.com
     */
    @RequestMapping("/sys/editProject")
    public ApiResult editProject(HttpServletRequest req, String project_time, Long project_id, String name,
                                 String pStr, String pic_id) {
        try {
            if (CommonUtils.checkMissParam(project_time, name)) {
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
            }
            int status = projectService.editProject(project_time, name, pStr, project_id, getBeamId(req), getUserId(req), pic_id);

            return status == 1 ? new ApiResult() : new ApiResult(HttpResultEnum.EXCEPTION.getCode());

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }

    /**
     * 工程初始化导入
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/sys/initProject",method = RequestMethod.POST)
    public ApiResult initProject(HttpServletRequest request, @RequestParam("excelFile")MultipartFile multipartFile){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        String projectId = request.getParameter("projectId");
        if(StringUtils.isEmpty(projectId) || multipartFile == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try{
            long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
            InputStream in = multipartFile.getInputStream();
            byte[] data = IOUtils.toByteArray(in);
            Workbook wb = null;
            FormulaEvaluator formulaEvaluator;
            try {
                wb = new HSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);
            } catch (Exception e) {
                wb = new XSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb);
            }
            result = projectService.initProject(wb,fileId, projectId, userId, beamId, formulaEvaluator, request);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }
        if(result == 0){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }else{
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"导入成功");
        }
    }
    /**
     * 根据项目id删除项目（物理删除）
     *
     * @param req
     * @param id
     * @return
     * @date 2018年6月13日
     * @author mintonzhang@163.com
     */
    @RequestMapping("/sys/delProject")
    public ApiResult delProject(HttpServletRequest req, Long id) {
        try {
            if (CommonUtils.checkMissParam(id)) {
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
            }
            projectService.delProject(getUserId(req), id, getBeamId(req));
            return new ApiResult();

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }

    /**
     * 根据id获取单个项目
     *
     * @param project_id
     * @return
     * @date 2018年6月13日
     * @author mintonzhang@163.com
     */
    @RequestMapping("/sys/getOneProject")
    public ApiResult getProjectById(String project_id, HttpServletRequest request) {
        Long beamId = super.getBeamId(request);
        if (CommonUtils.checkMissParam(project_id)) {
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
        }
        return new ApiResult(projectService.selectByPrimaryKey(project_id, beamId));
    }

    /**
     * 获取工程梁体详情
     *
     * @return
     */
    @RequestMapping("/sys/getProjectDetail")
    public PageResult getProjectDetail(HttpServletRequest request) {
        Long beamId = super.getBeamId(request);
        String projectId = request.getParameter("projectId");
        String productId = request.getParameter("productId");
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        if (StringUtils.isEmpty(projectId)) {
            return new PageResult(0,1,null);
        }
        List<ProjectDetail> projectDetails = projectService.getProjectDetails(projectId, productId, offset, limit, beamId);
        long total = projectService.countProjectDetails(projectId, productId, beamId);
        return new PageResult(total,CommonUtils.parseLong(offset,0),projectDetails);
    }

    /**
     * 获取工程产品
     * @param request
     * @return
     */
    @RequestMapping("/sys/getProjectDetail2")
    @ResponseBody
    public ApiResult getProjectDetail2(HttpServletRequest request){
        String project_detail_id = request.getParameter("project_detail_id");
        if(StringUtils.isEmpty(project_detail_id)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        Long beamId = super.getBeamId(request);
        ProjectDetail projectProducts  = projectService.getProjectDetail(project_detail_id, beamId);
        return new ApiResult(projectProducts);
    }

    @RequestMapping("/sys/getSelectProjectDrawing")
    @ResponseBody
    public ApiResult getSelectProjectDrawing(HttpServletRequest request){
    	String project_detail_id = request.getParameter("project_detail_id");
    	if(StringUtils.isEmpty(project_detail_id)){
    		return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
    	}
    	Long beamId = super.getBeamId(request);
    	List<ProductDrawingVO> productDrawingVOs  = projectService.getSelectProjectDrawing(project_detail_id, beamId);
    	return new ApiResult(productDrawingVOs);
    }

    /**
     * 删除梁
     * @param request
     * @return
     */
    @RequestMapping(value = "/sys/delProjectDetail", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult delProjectDetail(HttpServletRequest request){
        String id = request.getParameter("id");
        if(StringUtils.isEmpty(id)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        Long beamId = super.getBeamId(request);
        int i = projectService.delProjectDetail(id, beamId);
        if(i == 3){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "梁已开始生产，无法删除");
        }else if (i != 1){
            return new ApiResult();

        }else{
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 修改梁名称
     * @param request
     * @return
     */
    @RequestMapping(value = "/sys/updateProjectDetailName", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult updateProjectDetailName(HttpServletRequest request){
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        if(StringUtils.isBlank(id)||StringUtils.isBlank(name)){
            return new ApiResult(HttpResultEnum.MIS_PARAM);
        }
        return projectService.updateProjectDetailName(id, name);
    }

    /**
     * 增加导入梁
     * @param request
     * @return
     */
    @RequestMapping(value = "/sys/addProjectDetail", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult addProjectDetail(HttpServletRequest request, @RequestParam("excelFile")MultipartFile multipartFile){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        String projectId = request.getParameter("projectId");
        if(StringUtils.isEmpty(projectId) || multipartFile == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try{
            long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
            InputStream in = multipartFile.getInputStream();
            byte[] data = IOUtils.toByteArray(in);
            Workbook wb = null;
            FormulaEvaluator formulaEvaluator;
            try {
                wb = new HSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);
            } catch (Exception e) {
                wb = new XSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb);
            }
            result = projectService.addProjectDetail(wb,fileId, projectId, userId, beamId, formulaEvaluator);
        }catch (ApplicationException e){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }
        if(result == 0){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }else{
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"导入成功");
        }
    }

    /**
     * 获取工程产品材料详情
     *
     * @param request
     * @return
     */
    @RequestMapping("/sys/getProductSupplies")
    public PageResult getProductSupplies(HttpServletRequest request) {
        String projectId = request.getParameter("projectId");
        String productId = request.getParameter("productId");
        String projectDetailId = request.getParameter("projectDetailId");
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        if (StringUtils.isEmpty(productId) || StringUtils.isEmpty(projectId) || StringUtils.isEmpty(projectDetailId)) {
            return new PageResult(0, 0, null);
        }
        List<ProductSuppliesVo> productSuppliesVoList = projectService.getProductSupplies(projectId, productId, projectDetailId, offset, limit);
        for(ProductSuppliesVo p : productSuppliesVoList){
            //防止科学计数法
            if(p.getSuppliesNum().indexOf("E")>-1){
                BigDecimal bigDecimal = new BigDecimal(p.getSuppliesNum());
                p.setSuppliesNum(bigDecimal.toPlainString());
            }
        }
        long total = projectService.countProductSupplies(projectId, productId, projectDetailId);
        return new PageResult(total,CommonUtils.parseLong(offset,0), productSuppliesVoList);
    }

    /**
     * 修改工程产品材料数量
     * @param request
     * @return
     */
    @RequestMapping(value = "/sys/modifySuppliesNum",method = RequestMethod.POST)
    public ApiResult modifySuppliesNum(HttpServletRequest request){
        String suppliesNum = request.getParameter("suppliesNum");
        String project_detail_supplies_id = request.getParameter("project_detail_supplies_id");
        if(StringUtils.isEmpty(suppliesNum)||StringUtils.isEmpty(project_detail_supplies_id)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        Long userId = super.getUserId(request);
        try {
            return projectService.modifySuppliesNum(suppliesNum, project_detail_supplies_id, userId);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }
    }

}
